package com.my.util;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
/**
 * http://www.tuicool.com/articles/R7Rj6r3
 * jwt (JSON Web Tokens) 了解文章
 * 
 * 开发文档
 * https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home
 */
@Component
public class JWTUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(JWTUtil.class);

	
	private static byte[] sharedSecret  ;
	
	private static final String SHARED_SECRET_STR = "kA0WFucjXhEHxt08sy0oKVZkDLA8pUP874gK";
	/**
	 * 认证标示
	 */
	private static final String ISSUER_CLAIM = "http://www.xuninfo.cn";
	
	static {
		sharedSecret = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(SHARED_SECRET_STR);
	}
	
	//@Autowired
	//private IUserLoginMapperService userLoginMapperService;
	
	/**
	 * token校验
	 * @param token
	 * @return
	 * @throws ParseException
	 */
	public Boolean checkToken(String token){
		try {
			//判断token是否为空
			if(StringUtils.isBlank(token) || "null".equalsIgnoreCase(token.trim())){
				LOGGER.info("token={},校验失败 ",token);
				return Boolean.FALSE;
			}
			JWSObject jwsObject = JWSObject.parse(token);
			JWSVerifier verifier = new MACVerifier(sharedSecret);
			if(jwsObject.verify(verifier)){
				JWTClaimsSet claimsSet =  JWTClaimsSet.parse(jwsObject.getPayload().toJSONObject());
				return claimsSet.getIssuer().equals(ISSUER_CLAIM) && claimsSet.getExpirationTime().getTime() > System.currentTimeMillis();
			
				//return userLoginMapperService.isExist(appType, token);
			}
		} catch (Exception e) {
			LOGGER.info("token校验异常",e);
		}
		return Boolean.FALSE;
	}
	
	/**
	 * 创建token
	 * @param userId 根据userId创建令牌
	 * @return
	 */
	public String creatToken(String uid,Long tokenValidityTime){
	
		try {
			//设置负载部分
			JWTClaimsSet claimsSet =new JWTClaimsSet.Builder().subject(uid).expirationTime(new Date(tokenValidityTime)).issuer(ISSUER_CLAIM).build();
			//设置头部，负载
			JWSObject jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload(claimsSet.toJSONObject()) );
			//使用签名
			JWSSigner signer = new MACSigner(sharedSecret);
			//设置签名
			jwsObject.sign(signer);

			return jwsObject.serialize();//生成token
		} catch (JOSEException e) {
			LOGGER.info("token生成异常,被认证的目标是:{}",uid,e);
		}
		return null;
	}
	
	/**
	 * 根据token获取userId
	 * @param token
	 * @return
	 */
	public static String getUserIdByToken(String token){
		String userinfo = null;
		try {
			if(StringUtils.isBlank(token) || "null".equalsIgnoreCase(token.trim())|| token.length() < 12){
				LOGGER.info("根据token获取userId失败,token为空或者token不符合规范");
			}else{
				JWSObject jwsObject = JWSObject.parse(token);
				JWSVerifier verifier = new MACVerifier(sharedSecret);
				if(jwsObject.verify(verifier)){
					JWTClaimsSet claimsSet =  JWTClaimsSet.parse(jwsObject.getPayload().toJSONObject());
					if(claimsSet.getIssuer().equals(ISSUER_CLAIM)){
						return claimsSet.getSubject();
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("根据token获取userId异常,token={}",token,e);
		}
		return userinfo;
	}

}
